package com.lhgray.sglhome.presentation.ui.activity

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.graphics.Color

import androidx.core.content.ContextCompat
import androidx.lifecycle.ViewModelProvider
import com.freightoa.foundation.presentation.activity.BaseComposeActivity
import com.freightoa.foundation.presentation.composable.ErrorDialog
import com.freightoa.foundation.presentation.composable.LoadingDialog
import com.freightoa.foundation.presentation.composable.ProgressIndicatorNow
import com.freightoa.foundation.presentation.ext.toast
import com.freightoa.foundation.result.Router
import com.freightoa.foundation.result.Routes
import com.freightoa.foundation.utlis.showToast
import com.lhgray.sglhome.presentation.viewModel.HomeIntent
import com.lhgray.sglhome.presentation.viewModel.HomeState
import com.lhgray.sglhome.presentation.viewModel.HomeViewModel
import com.lhgray.sglhome.common.ScanQRContract
import com.lhgray.sglhome.presentation.ui.compose.HomePage
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject

@AndroidEntryPoint
class HomeActivity : BaseComposeActivity<HomeState, HomeIntent, HomeViewModel>() {

    @Inject
    lateinit var router: Router
    private val requestPermissionLauncher =
        registerForActivityResult(
            ActivityResultContracts.RequestPermission()
        ) { isGranted: Boolean ->
            if (isGranted) {
                startScan()
            } else {
                this.showToast("Permission denied")
            }
        }

    private val barcodeLauncher =
        registerForActivityResult(ScanQRContract()) { result: String ->
            val viewModel: HomeViewModel =
                ViewModelProvider(this@HomeActivity)[getViewModelClass()]
            viewModel.upBarcode(result)
        }

    private fun startScan() {
        barcodeLauncher.launch(null)
    }

    override fun getViewModelClass(): Class<HomeViewModel> = HomeViewModel::class.java


    override fun createInitialState() = HomeState.Loading()

    @Composable
    override fun Content(
        viewModel: HomeViewModel,
        state: HomeState,
        sendIntent: (HomeIntent) -> Unit,
        modifier: Modifier
    ) {
        Box(Modifier.background(color = Color.White)) {
            HomePage(viewModel, {
                if (ContextCompat.checkSelfPermission(
                        this@HomeActivity,
                        Manifest.permission.CAMERA
                    ) == PackageManager.PERMISSION_GRANTED
                ) {
                    startScan()
                } else {
                    requestPermissionLauncher.launch(Manifest.permission.CAMERA)
                }
            })
            when (state) {
                //is HomeState.Loading -> LoadingDialog(state.isLoading ?: false)
                is HomeState.Loading -> ProgressIndicatorNow(state.isLoading ?: false)
                is HomeState.Success -> Text(state.message ?: "")
                // is HomeState.Error -> DataNotFoundAnim()
                is HomeState.Error -> {
                    ErrorDialog(
                        showError = true,
                        onDismiss = { viewModel.handleIntent(HomeIntent.Idle) }, // 关闭时更新状态
                        message = state.errorMessage ?: "error"
                    )
                }

                HomeState.Idle -> {}
                is HomeState.NavigateToLogin -> {
                    // 执行跳转逻辑
                    LaunchedEffect(Unit) {
                        router.navigateTo(this@HomeActivity, Routes.LOGIN)
                        finish()
                    }
                }

                is HomeState.Toast -> state.message?.let { this@HomeActivity.toast(it) }
            }
        }
    }
}
